<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2021-08-24
 * Time: 17:59
 */

namespace app\services;

use app\models\Questions;
use app\models\QuestionSelects;
use app\models\UserAnswerRecords;
use app\models\UserAnswerStatistics;
use app\models\Users;
use think\facade\Db;

class QuestionService extends ServiceBase
{
    /**
     * @param array $select
     * @param int $page
     * @param int $pagesize
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($select = [], $page = 1, $pagesize = 10)
    {
        $news = Questions::lists($select, $page, $pagesize);

        return $news;
    }

    /**
     * @param $newsId
     * @return mixed
     * @throws \Exception
     */
    public function getDetail($newsId)
    {
        $question = Questions::find($newsId);

        if ($question instanceof Questions) {
            return $question;
        }

        throw new \Exception('题目不存在');
    }

    /**
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function create($params)
    {
        try {
            $question = new Questions();
            $question->questionTitle = $params['questionTitle'];
            $question->questionCategoryId = $params['questionCategoryId'];
            $question->rightCredit = $params['rightCredit'];
            $question->wrongCredit = $params['wrongCredit'];
            $question->status = 1;
            $question->save();

            if (isset($params['selects'])) {
                foreach ($params['selects'] as $key => $val) {
                    $select = new QuestionSelects();
                    $select->questionId = $question->questionId;
                    $select->selectContent = $val['selectContent'];
                    $select->isRight = $val['isRight'];
                    $select->sort = (new UtilService())->getAlphaSort($key);
                    $select->save();
                }
            }

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * @param Questions $question
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function update(Questions $question, $params)
    {
        try {
            foreach ($params as $key => $val) {
                $question->$key = $val;
            }
            $question->save();

            if (isset($params['selects'])) {
                QuestionSelects::where(['questionId' => $question->questionId])->delete();
                foreach ($params['selects'] as $key => $val) {
                    $select = new QuestionSelects();
                    $select->questionId = $question->questionId;
                    $select->selectContent = $val['selectContent'];
                    $select->sort = (new UtilService())->getAlphaSort($key);
                    $select->isRight = $val['isRight'];
                    $select->save();
                }
            }

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * @param Questions $question
     * @return bool
     * @throws \Exception
     */
    public function enable(Questions $question)
    {
        try {
            $question->status = 1;
            $question->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * @param Questions $question
     * @return bool
     * @throws \Exception
     */
    public function disable(Questions $question)
    {
        try {
            $question->status = 0;
            $question->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * @param Questions $question
     * @return bool
     * @throws \Exception
     */
    public function delete(Questions $question)
    {
        try {
            $question->delete();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * 获取随机一道题目
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRandQuestion()
    {
        $question = Questions::where('status', 1)->orderRaw('RAND()')->find();

        $data = $question->toArray();
        $data['questionCategoryKey'] = $question->category()->value('categoryKey');
        $data['selects'] = $question->selects;

        return $data;
    }

    /**
     * @param Users $user
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkAnswer(Users $user)
    {
        try {
            $year = date('Y');
            $month = date('m');
            $date = date('d');
            $todayLimit = 8;
            $dayLimit = 6;
            $process = 0;
            //获取这周的日期
            $days = (new UtilService())->getWeek();
            $thisWeekFirstDay = $days[1];
            $thisWeekLastDay = $days[7];
            //目前是定死的，一天最多回答20道题，一个月最多回答3天
            $statictis = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'month' => $month, 'date' => $date, 'type' => 1])->find();

            if ($statictis) {
                $process = $statictis->answerCount;
                if ($statictis->answerCount >= $todayLimit) {
                    throw new \Exception("<p>今天共获得".$statictis->creditCount."公益积分</p><p>今天答题次数已用完</p>", 500);
                }
            }

            $records = UserAnswerStatistics::where([
                ['userId', '=', $user->userId],
                ['type', '=',  1],
//                ['createdAt', '>=', $thisWeekFirstDay],
//                ['createdAt', '<=', $thisWeekLastDay],
            ])->order(['statictisId' => 'asc'])->select();

            $credit = 0;
            $day = '';
            foreach ($records as $record) {
                $credit += $record->creditCount;
                $day = date('Y-m-d', strtotime($record->createdAt));
            }

            if (count($records) >= $dayLimit && date('Y-m-d') > $day) {
                throw new \Exception("<p>共获得".$credit."公益积分</p><p>答题次数已用完</p>", 500);
            }

//            $count = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'month' => $month, 'type' => 1])->count();
//
//            if ($count > $dayLimit) {
//                $credit = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'month' => $month, 'type' => 2])->field('creditCount')->find();
//                throw new \Exception('本月共获得'.$credit->creditCount.'公益积分', 500);
//            }

            return ($process+1).'/'.$todayLimit;

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 答题
     * @param Users $user
     * @param Questions $question
     * @param $answer
     * @return UserAnswerRecords
     * @throws \Exception
     */
    public function answer(Users $user, Questions $question, $answer)
    {
        Db::startTrans();
        try {
            $record = new UserAnswerRecords();
            $record->userId = $user->userId;
            $record->questionId = $question->questionId;

            $select = QuestionSelects::find($answer);
            $record->isRight = $select->isRight;
            $record->credit = $select->isRight?$question->rightCredit:$question->wrongCredit;
            $record->answer = $select->sort;
            $record->save();

            $year = date('Y');
            $month = date('m');
            $date = date('d');
            //统计（日）
            $statictis = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'month' => $month, 'date' => $date, 'type' => 1])->find();
            if (!$statictis) {
                $statictis = new UserAnswerStatistics();
                $statictis->userId = $user->userId;
                $statictis->year = $year;
                $statictis->month = $month;
                $statictis->date = $date;
                $statictis->type = 1;
            }
            $statictis->answerCount +=1;
            $statictis->creditCount +=$record->credit;
            $statictis->save();


            //统计（月）
            $statictis = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'month' => $month, 'type' => 2])->find();
            if (!$statictis) {
                $statictis = new UserAnswerStatistics();
                $statictis->userId = $user->userId;
                $statictis->year = $year;
                $statictis->month = $month;
                $statictis->type = 2;
            }
            $statictis->answerCount +=1;
            $statictis->creditCount +=$record->credit;
            $statictis->save();

            //统计（年）
            $statictis = UserAnswerStatistics::where(['userId' => $user->userId, 'year' => $year, 'type' => 3])->find();
            if (!$statictis) {
                $statictis = new UserAnswerStatistics();
                $statictis->userId = $user->userId;
                $statictis->year = $year;
                $statictis->type = 3;
            }
            $statictis->answerCount +=1;
            $statictis->creditCount +=$record->credit;
            $statictis->save();

            Db::commit();
            return $record;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage(), $e->getCode());
        }
    }
}